import 'dart:async';

import 'package:flutter/material.dart';
import 'package:barcode_scan/barcode_scan.dart';
import 'package:flutter/services.dart';

class ScanPage extends StatefulWidget {
  @override
  _ScanPageState createState() =>_ScanPageState();
}

//。在需要指定异常类型时使用on。在异常处理程序需要异常对象时使用catch。
//您可以指定一个或两个参数来catch()。第一个是抛出的异常，第二个是堆栈跟踪(StackTrace对象)。

class _ScanPageState extends State<ScanPage> {
  String result = "Hey there !";

  Future _scanQR() async {
    try {
      String qrResult = await BarcodeScanner.scan();
      setState(() {
        result = qrResult;
      });
    } on PlatformException catch (ex) { //ios 异常
      if (ex.code == BarcodeScanner.CameraAccessDenied) {
        setState(() {
          result = "苹果摄像许可被拒绝";
        });
      } else {
        setState(() {
          result = "Unknown Error $ex";
        });
      }
    } on FormatException { //android 异常
      setState(() {
        result = "你在扫描之前按了后退键";
      });
    } catch (ex) {
      setState(() {
        result = "Unknown Error $ex"; //未知异常
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("QR Scanner"),
      ),
      body: Center(
        child: Text(
          result,
          style: new TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold),
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        icon: Icon(Icons.camera_alt),
        label: Text("Scan"),
        onPressed: _scanQR,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}
